package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class PeapWidgetProxy extends GeneralTestWidget {

    private WlanManager wlanManager;

    private Handler hander;

    private Activity ctx;

    private LinearLayout l;

    private ScrollView sv;
    private LinearLayout chartLayout;

    // private String mac;

    private static final String TAG = "ApRelevanceTest";

    private Button backBtn;

    private boolean connecting;

    public void setConnecting(boolean connecting) {
        this.connecting = connecting;
    }

    private int current;

    public void setCurrent(int current) {
        this.current += current;
    }

    private int timeout_num;// 超时次数;

    private int frequency;
    private int totalTime;
    private Task task;

    private double[] xdata;
    private double[] ydata;

    public PeapWidgetProxy(Activity context) {
        super(context);
        inflate(context, R.layout.aprelevance_test_widget_proxy, this);
        this.ctx = context;
        l = (LinearLayout) this.findViewById(R.id.aprelev_test_proxy_layout);
        sv = (ScrollView) findViewById(R.id.ap_test_proxy_ScrView);
        chartLayout = (LinearLayout) findViewById(R.id.apTestProxyChartLayout);
        backBtn = (Button) findViewById(R.id.ap_test_proxy_btnback);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });

        hander = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.DO_NEXT_TEST:
                    showNextText();
                    break;
                default:
                    update(msg.what);
                }
            }
        };

        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(hander);
        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        frequency = task.testCount;
        start(task.scanResult);

    }

    private void showNextText() {
        WebauthTestWidgetProxy ww = new WebauthTestWidgetProxy(ctx);
        ctx.setContentView(ww);
    }

    private void doNextTest() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                sendMsg(MessageWhat.DO_NEXT_TEST, hander);
            }
        };
        Timer t = new Timer();
        t.schedule(timerTask, TASK_PERFORM_INTERVAL);
        this.showMessage(ctx, "AP关联测试已完成，10秒后进入下一环节.");
    }

    private final class ApTestThread extends Thread {
        private ScanResult scan;

        public ApTestThread(final ScanResult scan) {
            this.scan = scan;
        }

        @Override
        public void run() {
            while (current < frequency && executable) {
                if (!connecting) {
                    current++;
                    connecting = true;
                    wlanManager.connect(scan);
                    //startConnectTimeoutListener();
                }
            }
        }

    }

    private void start(final ScanResult scan) {
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp != null) {
            xdata = new double[frequency];
            ydata = new double[frequency];
            final ApTestThread apTestThread = new ApTestThread(scan);
            this.showProgressDialog(ctx, "正在进行AP关联测试...", frequency);
            apTestThread.start();
        }
    }
    @Deprecated
    private void startConnectTimeoutListener() {
        TimerTask wifiReceiverTask = new TimerTask() {
            public void run() {
                if (connecting) {
                    Log.e(TAG, "AP关联第" + current + "测试连接超时");
                    wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
                    wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(wifiReceiverTask, WlanManager.CONNECT_TIMEOUT);
    }

    void update(int what) {
        setDialogProgress(current);
        switch (what) {
        case MessageWhat.WIFI_SUCESS_CONNECTED:
            if (connecting) {
                long costTime = (wlanManager.getConnectedConsumeTime() - wlanManager.getStartConntectTime()) / 1000;
                xdata[current - 1] = current;
                ydata[current - 1] = costTime;
                StringBuffer s = new StringBuffer();
                s.append("第").append(current).append("次关联AP点：");
                s.append(wlanManager.getCurrentScanResult().SSID).append(" MAC地址：");
                s.append(wlanManager.getCurrentScanResult().BSSID).append('\n');
                s.append("IP：").append(wlanManager.getIpAddress()).append(" 时间：");
                s.append(costTime).append(" s");
                totalTime += costTime;
                TextView tv = new TextView(ctx);
                tv.setTextSize(12);
                tv.setText(s);
                l.addView(tv);
                if (current == frequency) {
                    wlanManager.sendMsg(MessageWhat.DONE);
                }
                connecting = false;
            }
            break;
        case MessageWhat.WIFI_CONNECT_TIMEOUT:
            StringBuffer s = new StringBuffer();
            s.append("第").append(current).append("次关联 AP点：");
            s.append(wlanManager.getCurrentScanResult().SSID).append(" MAC地址：");
            s.append(wlanManager.getCurrentScanResult().BSSID).append("失败.");
            TextView tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            l.addView(tv);
            setTimeoutNum(1);
            if (current == frequency) {
                wlanManager.sendMsg(MessageWhat.DONE);
            }
            connecting = false;
            break;
        case MessageWhat.DONE:
            s = new StringBuffer();
            DecimalFormat df = new DecimalFormat("#0.000");
            int success = frequency - timeout_num;
            s.append("关联测试次数：").append(frequency);
            s.append(" 关联成功次数：").append(success).append('\n');
            s.append("关联成功率：").append((float) success / frequency * 100).append('%');
            s.append(" 关联平均时延：").append(df.format((float) (totalTime / frequency))).append('s');
            tv = new TextView(ctx);
            tv.setTextSize(13);
            tv.setTextColor(Color.CYAN);
            tv.setText(s);
            l.addView(tv);
            drawChart();

            task.relevanceAPAvgTime = df.format((float) (totalTime / frequency));
            task.relevanceAPSuccessRate = String.valueOf((float) success / frequency * 100);
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);

            this.dismissProgressDialog();
            doNextTest();
            connecting = false;
            break;
        }
        setScrollViewDown(sv);

    }

    private void drawChart() {
        ChartManager cm = new ChartManager(ctx, 5, 50);
        String chartTitle = "AP关联测试";
        String[] lineTitles = new String[] { "AP关联时间" };
        List<double[]> x = new ArrayList<double[]>(1);
        List<double[]> y = new ArrayList<double[]>(1);
        x.add(xdata);
        y.add(ydata);
        int[] colors = new int[] { Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        chartLayout.addView(lineChart);
    }

    private void setTimeoutNum(int timeout_num) {
        this.timeout_num += timeout_num;
    }

}
